<?php 
class ModelSettingSetting extends Model {
	public function getSetting($group, $restaurant_id = 0) {
		if($restaurant_id == 0) {
			$restaurant_id = $this->restaurant->getRestaurantId() == null? '0' : $this->restaurant->getRestaurantId();
		}
		
		$data = array(); 
		
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "setting WHERE restaurant_id = '" . (int)$restaurant_id . "' AND `group` = '" . $this->db->escape($group) . "'");
		
		foreach ($query->rows as $result) {
			if (!$result['serialized']) {
				$data[$result['key']] = $result['value'];
			} else {
				$data[$result['key']] = unserialize($result['value']);
			}
		}

		return $data;
	}
	
	public function getTotalSettings($data = array()) {
		$sql = "SELECT COUNT(setting_id) AS total FROM " . DB_PREFIX . "setting";
		
		$sql .= " WHERE 1 = 1";
	 	
		if (!empty($data['key'])) {
			$sql .= " AND `key` = '" . $this->db->escape($data['key']) . "'";
		}

		if (!empty($data['value'])) {
			$sql .= " AND `value` = '" . $this->db->escape($data['value']) . "'";
		}

		if (!empty($data['group'])) {
			$sql .= " AND `group` = '" . $this->db->escape($data['group']) . "'";
		}
		
		if (!empty($data['restaurant_id'])) {
			$sql .= " AND restaurant_id = '" . (int)$data['restaurant_id'] . "'";
		}

		$query = $this->db->query($sql);
		
		return $query->row['total'];
	}
	
	public function editSetting($group, $data, $restaurant_id = 0) {
		if($restaurant_id == 0) {
			$restaurant_id = $this->restaurant->getRestaurantId() == null? '0' : $this->restaurant->getRestaurantId();
		}
		
		$this->db->query("DELETE FROM " . DB_PREFIX . "setting WHERE restaurant_id = '" . (int)$restaurant_id . "' AND `group` = '" . $this->db->escape($group) . "'");

		foreach ($data as $key => $value) {
			if (!is_array($value)) {
				$this->db->query("INSERT INTO " . DB_PREFIX . "setting SET restaurant_id = '" . (int)$restaurant_id . "', `group` = '" . $this->db->escape($group) . "', `key` = '" . $this->db->escape($key) . "', `value` = '" . $this->db->escape($value) . "'");
			} else {
				$this->db->query("INSERT INTO " . DB_PREFIX . "setting SET restaurant_id = '" . (int)$restaurant_id . "', `group` = '" . $this->db->escape($group) . "', `key` = '" . $this->db->escape($key) . "', `value` = '" . $this->db->escape(serialize($value)) . "', serialized = '1'");
			}
		}
	}
	
	public function deleteSetting($group, $restaurant_id = 0) {
		if($restaurant_id == 0) {
			$restaurant_id = $this->restaurant->getRestaurantId() == null? '0' : $this->restaurant->getRestaurantId();
		}
		
		$this->db->query("DELETE FROM " . DB_PREFIX . "setting WHERE restaurant_id = '" . (int)$restaurant_id . "' AND `group` = '" . $this->db->escape($group) . "'");
	}
}
?>